#    Copyright 2008, 2009, 2012 Tri-County Electric Cooperative, St. Matthews, South Carolina
#    This file is part of COOPWeb.
#    COOPWeb is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#    COOPWeb is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#    You should have received a copy of the GNU General Public License
#    along with COOPWeb.  If not, see <http://www.gnu.org/licenses/>.

import os
import datetime
import shutil

#************************BEGIN Add Include Files to Path************************
import sys
NeededPaths=['/opt/coopweb/djangoproject/include', '/opt/coopweb/djangoproject']
for path in NeededPaths:
    if(not path in sys.path):
        sys.path.append(path)
#************************END   Add Include Files to Path************************
from django.contrib.gis.geos import *
import os, time, psycopg2, datetime
#********************Setup psycopg2 and django section********************
PathDjangoRoot="/opt/coopweb/"
if(not PathDjangoRoot in sys.path):
    sys.path.append(PathDjangoRoot)
from django.core.management import setup_environ
import djangoproject
from djangoproject import settings
setup_environ(settings)
from models import *
#********************Setup psycopg2 and django section********************

from django.template import Context, loader
from django.http import HttpResponse
from django import forms
import os
import datetime
import djangoproject.settings
import COOPWeb_Misc, COOPWeb_FormMeter, COOPWeb_FormAlarm


def BuildAndProcessMeterForm(request, FailedMeters, ActiveButNotAuthorizedMeters, NotFoundMeters, ServiceOrderMeters, InvestigationMeters): 
    ProcessMeterFormRequest(request) #need to process directly from request, then get lists of meters, but do that after getting basics working
    FormDictionary=BuildMeterForm(FailedMeters, ActiveButNotAuthorizedMeters, NotFoundMeters, ServiceOrderMeters, InvestigationMeters)
    if request.method == 'POST':  #Setup the form so it can be processed/modified on this postback
        form=COOPWeb_Misc.DynForm()
        form.setFields(FormDictionary)
        form.setData(request.POST)
        data={}
        for i in form.data.keys():  #Copy the Form Data to a dictionary then back to the form so it can be modified for the next screen view
            data[i] = form.data[i]
        form.data = data
    else:   #Otherwise, setup the Boolean values checked for processing to false
        form=COOPWeb_Misc.DynForm()
        form.setFields(FormDictionary)
        form.data={}
    return form


def FormGetBoolean(form, FieldName):
    try:
        Result=bool(form.data[FieldName] == 'on')
    except:
        Result=False
    return Result

def FormGetFloat(form, FieldName, Default=0):
    try:
        String=form.data[FieldName]
    except:
        return Default
    String = String.replace(',', '')
    try:
        Result=float(String)
    except:
        Result=Default
    return Result

def FormGetInteger(form, FieldName, Default=0):
    try:
        return int(FormGetFloat(form, FieldName, Default))
    except:
        return Default





def GetAlphaNumericCommasOnly(String):
    NewStringList=[]
    for i in String:
        if(i in 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890,'):
            NewStringList.append(i)
    return ''.join(NewStringList)

def FormGetList(form, FieldName, Default=[], Strip=True):
    String=FormGetString(form, FieldName, Default='')
    if(Strip):
        GetAlphaNumericCommasOnly(String)
    StringList=String.split(',')
    ListWithNoEmptyStrings=[]
    for i in StringList:
        if(i):
            ListWithNoEmptyStrings.append(i)
    return ListWithNoEmptyStrings



def FormGetString(form, FieldName, Default=''):
    try:
        Result=form.data[FieldName]
    except:
        Result=Default
    return Result



def StringToDate(DateString):
    """Attempts To Convert:
    'YYYY-MM-DD' to a Date 
    'MM/DD/YYYY', 'MM/YYYY', or 'YYYY' to a Date"""
    if(not DateString):
        return None
    if(DateString.find('-') <> -1):
        Split=DateString.split('-')
        Year=int(Split[0])
        Month=int(Split[1])
        Day=int(Split[2][:2])
    elif(DateString.find('/') <> -1):        
        Split=DateString.split('/')
        if(len(Split) == 3):
            Year=int(Split[2])
            Month=int(Split[0])
            Day=int(Split[1])
        elif(len(Split) == 2):
            Year=int(Split[1])
            Month=int(Split[0])
            Day=1
        else:
            Year=int(Split[0])
            Month=1
            Day=1
    else:
        Year=int(DateString)
        Month=1
        Day=1
    return datetime.date(Year, Month, Day)

def StringDateTimeToDateTime(DateTimeString):
    """Attempts To Convert:
    'YYYY-MM-DD HH-MM-SS.SSS...' to a DateTime,
    returns None if it fails,
    for example: 
               '2008-09-26 15:05:43.222615'
    to:  datetime.datetime(2008, 9, 26, 15, 5, 43, 222615)"""
    if(not DateTimeString):
        return None
    try:
        Year=int(DateTimeString[:4])
        Month=int(DateTimeString[5:7])
        Day=int(DateTimeString[8:10])
        Hour=int(DateTimeString[11:13])
        Minute=int(DateTimeString[14:16])
        Second=int(DateTimeString[17:19])  
        PartialSeconds=int(DateTimeString[20:])
        return datetime.datetime(Year, Month, Day, Hour, Minute, Second, PartialSeconds)
    except:
        return StringToDate(DateTimeString)

def String_MM_DD_YYYY_HH_MM__Or_HH_MM_ToDateTime(DateTimeString):
    """Attempts to Convert:  
    'MM-DD-YYYY HH-MM' to a datetime
    Otherwise, converts a:
    'HH-MM' to a datetime, with a date of today
    """

    if(not DateTimeString):
        return None
    DateTimeString=DateTimeString.lower()
    if('p' in DateTimeString):
        PMIndicator=True
    else:
        PMIndicator=False
    FilteredStringList=[]
    for i in DateTimeString:
        if(i in '0123456789'):
            FilteredStringList.append(i)
        else:
            FilteredStringList.append(' ')
    SplitString=''.join(FilteredStringList).split(' ')
    NoEmptyElements=[]
    for i in SplitString:
        if(i):
            NoEmptyElements.append(i)
    if(not len(NoEmptyElements) in [2, 5]):
        return None
    if(len(NoEmptyElements) == 2):
        Hour = int(NoEmptyElements[0])
        if(PMIndicator):
            Hour=Hour + 12
        Minute=int(NoEmptyElements[1])
        Year=datetime.datetime.now().year
        Month=datetime.datetime.now().month
        Day=datetime.datetime.now().day
    else:
        Month=int(NoEmptyElements[0])
        Day=int(NoEmptyElements[1])
        Year=int(NoEmptyElements[2])
        Hour=int(NoEmptyElements[3])
        if(PMIndicator):
            Hour = Hour + 12
        Minute=int(NoEmptyElements[4])
    return datetime.datetime(Year, Month, Day, Hour, Minute)


def FormGetDateTime(form, FieldName):
    String=FormGetString(form, FieldName)
    try:
        DateTime=StringDateTimeToDateTime(String)
    except:
        return None
    return DateTime


def FormGetDateTime2(form, FieldName):
    String=FormGetString(form, FieldName)
    try:
        DateTime=String_MM_DD_YYYY_HH_MM__Or_HH_MM_ToDateTime(String)
    except:
        return None
    return DateTime




def FormGetGeographicData(form, FieldName):
    try:
        return fromstr(form.data[FieldName])
    except:
        return None

def FormGetObjectFromid(form, FieldName, Object):
    Objectid=FormGetInteger(form, FieldName)
    if(id):
        Result=Object.objects.all().filter(id=Objectid)
    else:
        return None
    if(Result):
        return Result[0]
    else:
        return None











class LoginForm(forms.Form):
    Username=forms.CharField(widget=forms.TextInput(attrs={'size':'5.5'}))
    Password=forms.CharField(widget=forms.PasswordInput(attrs={'size':'5.5'}))






def BuildDynamicForm(request, FormName, SpecialBuildFormDataDict={}):
    if(FormName=='MeterPing'):
        FormDictionary=COOPWeb_FormMeter.BuildMeterPingForm(SpecialBuildFormDataDict)
    elif(FormName=='AlarmTable'):
        FormDictionary=COOPWeb_FormAlarm.BuildAlarmTableForm(SpecialBuildFormDataDict)
    else:
        raise(Exception('An Invalid Form Name was specified in BuildForm in COOPWeb_Form.py'))
    if request.method == 'POST':  #Setup the form so that it can be processed/modified on this postback
        form=COOPWeb_Misc.DynForm()
        form.setFields(FormDictionary)
        form.setData(request.POST)
        data={}
        for i in form.data.keys():     #Copy the Form Data to a dictionary then back to the form so that it can be modified for the next screen view
            data[i] = form.data[i]
        form.data = data
    else:  #Otherwise, setup the Boolean Values checked for processing to false
        form=COOPWeb_Misc.DynForm()
        form.setFields(FormDictionary)
        form.data={}
    return form


  








